package controllers;

import java.util.List;

import models.Book;
import models.Cover;
import models.ReadingSheet;
import play.Logger;
import play.data.validation.Error;
import play.data.validation.Validation;
import play.mvc.Controller;

//TODO @With(Secure.class)
public class ReadingSheetMngt extends Controller {

	protected static final String FROM_ADDING_FORM = "addingsheet";
	protected static final String FROM_UPDATING_FORM = "updatingsheet";
	
    public static void index() {
        render();
    }
    
    
    public static void displayList() {
        
    	Long userId = Security.getConnectedUser().getId();
    	
    	List<ReadingSheet> list = ReadingSheet.find("select r from ReadingSheet r " +
    			"join fetch r.book b " + // join fetch pour recup les données de la jointure
    			"join fetch b.author a " +
    			"left join fetch b.collection c " +
    			"where r.user.id = ? ", userId).fetch();

    	
    	render(list);
    }
    
    public static void displayOne(final Long sheetId) {
    	Long userId = Security.getConnectedUser().getId();
    	
    	ReadingSheet sheet = ReadingSheet.findById(sheetId);
    	
    	validation.equals(sheet.user.id, userId);
    	if (Validation.hasErrors()) {
    		internalPerformError();
    		error("Vous ne pouvez pas accéder cette fiche !");
    	}
    	
    	List<Cover> covers = Cover.find("book = ? order by ordernum", sheet.book).fetch(); 
    	
    	render(sheet, covers);
    }
    
    /**
     * Prepare the add form.
     * @throws Throwable 
     */
    public static void addForm() {
    	Long userId = Security.getConnectedUser().getId();
    	
    	List<Book> bookList = Book.find("select b from Book b " +
    			"where not exists (" +
    			"select r.id " +
    			"from ReadingSheet r " +
    			"where r.book = b " +
    			"and r.user.id = ?)", userId).fetch();
    	
    	//TODO preselectionner le livre qui vient d'être ajouté
    	
    	renderArgs.put("from", FROM_ADDING_FORM);
    	render(bookList, userId);
    }
    
    
    public static void updateForm(final Long sheetId) {
    	Long userId = Security.getConnectedUser().getId();
    	
    	ReadingSheet readingsheet = ReadingSheet.findById(sheetId);
    	
    	renderArgs.put("from", FROM_UPDATING_FORM);
    	
    	render(readingsheet, userId);
    }

//    @Before(only = "add")
    // not public with @before
//    static void addBefore(ReadingSheet readingsheet) {
//    }
    
    /**
     * Add the sheet.
     * @throws Throwable 
     */
    public static void add(final ReadingSheet readingsheet) {
    	
    	readingsheet.user = Security.getConnectedUser();
    	validation.valid(readingsheet);
    	
    	if (Validation.hasErrors()) {
    		internalPerformError();
    		addForm();
    	} 
    		
    	// else
        readingsheet.create();
        displayList();
    	
    }
    
    public static void update(final ReadingSheet readingsheet) {
    	
    	readingsheet.user = Security.getConnectedUser();
    	validation.valid(readingsheet);
    	
    	if (Validation.hasErrors()) {
    		internalPerformError();
    		updateForm(readingsheet.id);
    	} 
    		
    	// else
        readingsheet.save();
        displayList();
    	
    }
    
    
    
    private static void internalPerformError() {
    	
		if (Logger.isDebugEnabled()) {
			Logger.debug("Erreur trouvée dans création/modification readingsheet");
			for (Error err : Validation.errors()) {
				Logger.debug(err.message() + " --> pour le champ " + err.getKey());
			}
		}
		
		params.flash(); // add http parameters to the flash scope
		validation.keep(); // keep the erros for the next request
    
    }

}
